package com.smartdot.bluetoothidcarddemo;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcV;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;

import com.smartdot.bluetoothidcarddemo.camera.CameraHelper;
import com.smartdot.bluetoothidcarddemo.camera.FaceView;
import com.smartdot.bluetoothidcarddemo.nfc.BaseNfcActivity;
import com.smartdot.bluetoothidcarddemo.utils.ImageUtils;
import com.smartdot.bluetoothidcarddemo.utils.LogUtils;
import com.smartdot.bluetoothidcarddemo.utils.StatusBarUtil;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class CameraActivity extends BaseNfcActivity implements View.OnClickListener {
    private SurfaceView surfaceView;
    private ImageView ivTakePic;
    private ImageView ivExchange;
    private CameraHelper cameraHelper;
    private FaceView faceView;
    private ImageView imageView3;
    private boolean hasFace = false;
    private boolean isFront = true;// 是否执行
    private boolean isCamera = false;// 是否获取照片
    private boolean isAllowFaceDetect = true;// 是否允许人脸检测
    private int mCount = 0;// 是否执行
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            if (isFront && hasFace) {
                isCamera = true;
            }else {
                isCamera = false;
            }
        }
    };
    private String base64String;
    private AlertDialog.Builder builder;

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarColor(this, getColor(R.color.translate), true);
        StatusBarUtil.StatusBarLightMode(this);
        if (Build.VERSION.SDK_INT >= 23) {
            requestPermission();
        } else {
            initCamera();
        }
        resolveIntent(getIntent());
    }

    private void initCamera() {

        setContentView(R.layout.customcamera_layout);
        surfaceView = findViewById(R.id.surfaceView);
        faceView = findViewById(R.id.faceView);
        imageView3 = findViewById(R.id.imageView3);
        ivExchange = findViewById(R.id.ivExchange);
        ivTakePic = findViewById(R.id.ivTakePic);
        ivExchange.setOnClickListener(this);
        ivTakePic.setOnClickListener(this);
        ivTakePic.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return false;
            }
        });
        timer.schedule(task, 0, 2000);
        cameraHelper = new CameraHelper(this, surfaceView);
        cameraHelper.addCallBack(new CameraHelper.CallBack() {
            @Override
            public void onPreviewFrame(byte[] data, int[] parameter, Camera camera) {
                // 预览数据 要显示照片  需要转化一下

                if (hasFace && isCamera) {
                    isAllowFaceDetect = false;
                    isCamera = false;
                    hasFace = false;
                    Camera.Size previewSize = camera.getParameters().getPreviewSize();
                    BitmapFactory.Options newOpts = new BitmapFactory.Options();
                    newOpts.inJustDecodeBounds = true;
                    YuvImage yuvimage = new YuvImage(
                            data,
                            ImageFormat.NV21,
                            previewSize.width,
                            previewSize.height,
                            null);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 100, baos);// 80--JPG图片的质量[0-100],100最高
                    byte[] rawImage = baos.toByteArray();
                    //将rawImage转换成bitmap
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inPreferredConfig = Bitmap.Config.RGB_565;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length, options);
                    // 获取一张后处理  暂停预览以及人脸检测
                    cameraHelper.stopFaceDetection();
                    showPicture(bitmap, parameter);
                }
            }

            @Override
            public void onTakePic(byte[] data, int[] parameter) {
                // 手动点击拍照按钮或程序定时拍照回调
                //得到数据bitmap
//                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//                showPicture(bitmap, parameter);
            }

            @Override
            public void onFaceDetect(Camera.Face[] faces) {
//                LogUtils.eNormal("luoli:人脸检测数据", "检测到" + faces.length + "张人脸");
                if (faces.length > 0 && isAllowFaceDetect) {
                    hasFace = true;
                } else {
                    hasFace = false;
                }

                ArrayList<RectF> rectFS = cameraHelper.transForm(faces);
                // 绘制脸部描框
                faceView.setFaces(rectFS);
            }
        });
    }

    /**
     * 保存照片
     */
    private void showPicture(Bitmap originalBitmap, int[] parameter) {
//        LogUtils.eNormal("luoli:保存数据", "=========保存数据=========");
        if (originalBitmap == null) {
            return;
        }
        Bitmap bitmap = getProcessBitmap(originalBitmap, parameter);

        Bitmap compressImage = ImageUtils.compressImage(bitmap, 200);
        imageView3.setImageBitmap(compressImage);
        saveToFolder(compressImage);
        base64String = ImageUtils.bitmap2Base64(compressImage, 200);
        // 拍照完成 上传
        builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setCancelable(false);
        builder.setMessage("拍照完成 点击确认上传");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                showNfcDialog("拍照上传完成，请读取卡片");
            }
        });
        builder.setNegativeButton("重拍", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                isAllowFaceDetect = true;
                cameraHelper.reStartFaceDetection();
            }
        });
        LogUtils.eNormal("luoli:", "====拍照ok  显示对话框=========");
        builder.show();
    }


    private void showNfcDialog(String s) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setCancelable(false);
        builder.setMessage(s);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                isAllowFaceDetect = true;
                cameraHelper.reStartFaceDetection();
            }
        });
//        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//
//            }
//        });
        builder.show();
    }

    private void submit() {

    }

    /**
     * 处理图片 使其向正确的方向旋转
     */
    private Bitmap getProcessBitmap(Bitmap originalBitmap, int[] parameter) {
        Bitmap bitmap = null;
        int rotation = parameter[0];
        switch (rotation) {
            case 0:
                // 竖屏
                if (cameraHelper.mCameraFacing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    bitmap = mirror(rotate(originalBitmap, 270f));
                } else {
                    bitmap = rotate(originalBitmap, 90f);
                }
                break;
            case 1:
                // 向左横屏（Home键在右侧）
                if (cameraHelper.mCameraFacing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    bitmap = mirror(rotate(originalBitmap, 0f));
                } else {
                    bitmap = rotate(originalBitmap, 0f);
                }
                break;
            case 3:
                // 向左横屏（Home键在右侧）
                if (cameraHelper.mCameraFacing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    bitmap = mirror(rotate(originalBitmap, 180f));
                } else {
                    bitmap = rotate(originalBitmap, 180f);
                }
                break;
            default:
                // 默认竖屏竖屏
                if (cameraHelper.mCameraFacing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    bitmap = mirror(rotate(originalBitmap, 270f));
                } else {
                    bitmap = rotate(originalBitmap, 90f);
                }
                break;
        }
        return bitmap;
    }

    /**
     * 将获取到的图片保存到本地
     */
    private void saveToFolder(Bitmap bitmap) {

        //并没有进行处理 你也可以把他储存到内存卡上 把bitmap进行封装
        //buffer缓冲 outPut输出 steam流 缓冲输入流初始化
        BufferedOutputStream bufferedOutputStream = null;
        try {
            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/AndroidPhoto/";
            File _file = new File(filePath);
            if (!_file.exists()) {
                _file.mkdir();
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH时mm分ss秒");
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh时");
            String fileName = "luoli_" + format.format(new Date()) + ".jpg";
            //设置文件名
            filePath = filePath + fileName;
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            } else {
                file.delete();
            }
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
            //保存  100压缩率 按原图保存
            //compress压缩 format格式 100 缓冲输出流
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bufferedOutputStream);
            //对图片进行压缩  设置输出流为内容
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //最后对所用到的东西进行关闭 以免内存泄漏
            //防止使用后用户打开其他软件会出现bug
            if (bufferedOutputStream != null) {
                //判断输出流是否为空
                try {
                    //对输出流进行关闭
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    //抛出异常
                    e.printStackTrace();
                }
            }
        }
    }

    //    -------------------------NFC-----------------------

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        resolveIntent(intent);
    }

    private void resolveIntent(Intent intent) {
        String action = intent.getAction();
        LogUtils.eNormal("luoli", "action:" + action);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            // 获取卡片的Id
            byte[] id = mTag.getId();
            String s = printHexString(id);
            showNfcDialog(s);
            LogUtils.eNormal("luoli", "哈哈哈:" + s);
            String[] techList = mTag.getTechList();
            for (String tech : techList) {
                if (tech.equals(NfcV.class.getName())) {
//                    readNfcV();
                }
            }
        }
    }

    /**
     * 将字节数组遍历转换为16进制并拼接为String
     */
    private String printHexString(byte[] data) {
        StringBuffer s = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            String hex = Integer.toHexString(data[i] & 0xFF).toUpperCase();
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            if (i != data.length - 1) {
                s.append(hex + ":");
            } else {
                s.append(hex);
            }
        }
        return s.toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isFront = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isFront = false;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ivTakePic) {
            cameraHelper.takePic();
        } else if (id == R.id.ivExchange) {
            // 切换摄像头后清除人脸检测描框
            faceView.clearFaces();
            cameraHelper.exchangeCamera();
        }
    }

    //水平镜像翻转
    private Bitmap mirror(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(-1f, 1f);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    //旋转
    private Bitmap rotate(Bitmap bitmap, Float degree) {
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    @Override
    protected void onDestroy() {
        //release释放
        releaseCamera();
        timer.cancel();
        super.onDestroy();
    }

    //release释放
    private void releaseCamera() {
        //如果相机不为空 释放相机
        if (cameraHelper != null) {
            cameraHelper.releaseCamera();
        }
    }

    /**
     * 请求权限
     */
    private void requestPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(CameraActivity.this, new String[]{Manifest.permission.CAMERA
                    , Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        } else {
            initCamera();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            //如果requestCode为100 就走这里
            case 100:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    initCamera();
                } else {
                    //因为第一次的对话框是系统提供的 从这以后系统不会自动弹出对话框 我们需要自己弹出一个对话框
                    //进行询问的工作
                    startAlertDiaLog();
                }

                break;

        }

    }

    public void startAlertDiaLog() {

        android.app.AlertDialog.Builder alert = new android.app.AlertDialog.Builder(this);

        alert.setTitle("提示");
        alert.setMessage("需要申请权限");
        alert.setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                //这里的立即开启 是打开手机的设置页面(打开相机权限)
                startSetting();

            }
        });
        alert.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //如果用户还不打开 只能等用户下次点击时再次询问
//                Toast.makeText(BlueToothActivity.this,"当您点击我们会再次询问",Toast.LENGTH_SHORT).show();

            }
        });
        alert.create();
        alert.show();

    }

    public void startSetting() {

        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);

        Uri uri = Uri.fromParts("package", getPackageName(), null);

        intent.setData(uri);

        startActivityForResult(intent, 10);

    }
}

